<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.Name" placeholder="字段名" @keydown.enter="searchForm"> </el-input>

				<el-button size="default" @click="searchForm" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<tableTem ref="tableRef" v-bind:="state.tableData" @pageChange="onTablePageChange">
				<el-table-column align="center" type="index" label="序号" width="60" />
				<el-table-column align="center" min-width="120" prop="fieldName" label="字段名"></el-table-column>
				<el-table-column align="center" prop="fieldDisplayName" min-width="150" label="显示名称"></el-table-column>
				<el-table-column align="center" prop="fieldTypeName" min-width="120" label="字段类型"></el-table-column>
				<el-table-column align="center" prop="fieldCount" min-width="120" label="是否索引">
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.checkScript == '1'">是</el-tag>
						<el-tag type="info" v-else>否</el-tag>
					</template>
				</el-table-column>

				<el-table-column label="操作" align="center" width="190" fixed="right">
					<template #default="scope">
						<el-button size="small" type="primary" text @click="editOption(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" text @click="onRowDel(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</tableTem>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			:title="state.isEdit ? '编辑模型' : '新增模型'"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="500px"
		>
			<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="字段名" prop="fieldName">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.fieldName" class="w_250 mr10" placeholder="请输入字段名" clearable></el-input>
								<el-tooltip
									class="item"
									effect="dark"
									content="2-30位英文字母、数字、下划线的组合，以英文字母开头，如'deviceId'"
									placement="right-end"
								>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="显示名称" prop="fieldDisplayName">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.fieldDisplayName" class="w_250 mr10" placeholder="请输入显示名称" clearable></el-input>
								<el-tooltip class="item" effect="dark" content="字段显示名称，一般为中文，如'设备ID'" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="字段类型" prop="fieldType">
							<div class="flex-c-c">
								<el-select class="w_250 mr10" v-model="state.ruleForm.fieldType" size="default">
									<el-option v-for="item in state.fieldStatus" :key="item.enumValue" :label="item.desction" :value="item.enumValue"></el-option>
								</el-select>
								<el-tooltip class="item" effect="dark" placement="right-end">
									<template #content>
										<div>
											字段类型，目前有四种类型，分别为字符串（如'你好'，abc'等），整数（其范围为 -2147483648 到 2147483647 之间）
											<br />长整数（其范围为 -9223372036854775808 到 9223372036854775807 之间），浮点数（如 3.14）。
										</div>
									</template>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="是否索引" required>
							<el-switch v-model="state.ruleForm.checkScript" :active-value="'1'" :inactive-value="'0'" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-btn">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { RiskFieldGetPagedList, RiskFieldDelete, RiskFieldCreate, RiskFieldUpdate } from '/@/api/model/index';
import { GetEnumberOptions } from '/@/api/common/index';
// 引入组件
const tableTem = defineAsyncComponent(() => import('/@/components/tables/index.vue'));
// 定义父组件传过来的值
const props = defineProps({
	modelId: {
		type: [Number, String],
		default: () => '',
	},
});
// 定义变量内容
const tableRef = ref();
const modelListFef = ref();
const listQuery = reactive({
	Name: '', //名称
});
const state = reactive<any>({
	tableData: {
		data: [],
		total: 0,
		loading: true,
		param: {
			PageIndex: 1,
			PageSize: 10,
		},
	},
	fieldStatus: [], // 字段类型
	ruleForm: {
		fieldDisplayName: '',
		fieldName: '',
		fieldType: '',
		checkScript: '0',
		id: '',
	} as any, // 新增
	dialogVisible: false, // 弹窗状态
	isEdit: false, //是否编辑
});
// 页面加载时
onMounted(() => {
	getTableData();
});

// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const params = {
			...state.tableData.param,
			...listQuery,
			modelId: props.modelId,
		};
		Object.keys(params).forEach((key) => {
			if (!params[key]) delete params[key];
		});
		let data = await RiskFieldGetPagedList(params);
		state.tableData.data = data.data.items;
		state.tableData.total = data.data.totalCount;
	} finally {
		state.tableData.loading = false;
	}
};

// 新增
const addRule = () => {
	state.ruleForm.fieldDisplayName = '';
	state.ruleForm.fieldName = '';
	state.ruleForm.fieldType = '';
	state.ruleForm.checkScript = '0';
	state.dialogVisible = true;
	state.isEdit = false;
	if (!state.fieldStatus.length) GetFieldTypes();
};
// 编辑
const editOption = (item: any) => {
	state.ruleForm.fieldDisplayName = item.fieldDisplayName;
	state.ruleForm.fieldName = item.fieldName;
	state.ruleForm.fieldType = item.fieldType;
	state.ruleForm.checkScript = item.checkScript;
	state.ruleForm.id = item.id;
	state.dialogVisible = true;
	state.isEdit = true;
	if (!state.fieldStatus.length) GetFieldTypes();
};

// 删除账户
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久删除模型信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskFieldDelete([id]);
		ElMessage.success('删除成功');
		getTableData();
	});
};
// 分页改变
const onTablePageChange = (val: any) => {
	state.tableData.param.PageIndex = val.pageNum;
	state.tableData.param.PageSize = val.pageSize;
	getTableData();
};
// 搜索点击时表单回调
const searchForm = () => {
	state.tableData.param.PageIndex = 1;
	tableRef.value.pageReset();
};
// 重置
const resetForm = () => {
	listQuery.Name = '';
	searchForm();
};

// 关闭弹窗
const onCancel = () => {
	state.dialogVisible = false;
};

const rules = reactive({
	fieldName: [{ required: true, message: '请输入字段名', trigger: ['blur', 'change'] }],
	fieldDisplayName: [{ required: true, message: '请输入显示名称', trigger: ['blur', 'change'] }],
	fieldType: [{ required: true, message: '请选择字段类型', trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: props.modelId,
			};
			if (state.isEdit) {
				await RiskFieldUpdate(params, state.ruleForm.id);
			} else {
				delete params.id;
				await RiskFieldCreate(params);
			}
			ElMessage.success(state.isEdit ? '修改成功' : '新增成功');
			onCancel();
			resetForm();
		}
	});
};
//  风控字段
const GetFieldTypes = async () => {
	let data = await GetEnumberOptions({ enumName: 'RiskFieldTypeEnum' });
	state.fieldStatus = data.data;
};
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
</style>
